package cn.doyens.reggie.service.impl;

import cn.doyens.reggie.common.CustomException;
import cn.doyens.reggie.entity.Category;
import cn.doyens.reggie.entity.Dish;
import cn.doyens.reggie.entity.Setmeal;
import cn.doyens.reggie.mapper.CategoryMapper;
import cn.doyens.reggie.service.CategoryService;
import cn.doyens.reggie.service.DishService;
import cn.doyens.reggie.service.SetmealService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {


    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;


    @Override
    public void removeCategory(Long catetoryId) {

        //1.查询dish表中是否有菜品信息与要删除的分类id 关联
        QueryWrapper<Dish> dishQueryWrapper = new QueryWrapper<>();
        dishQueryWrapper.eq("category_id",catetoryId);
        //返回dish表中 有几条条目与当前的分类id 有关联
        int dishCount = dishService.count(dishQueryWrapper);
        //判断dishCount 是否大于0
        if(dishCount>0){
            //手动抛出异常
            throw new CustomException("该分类与菜品关联 删除失败"); //NullPointerException
        }
        //2.查询setmeal表中 是否有套餐与要删除的分类id有关联
        LambdaQueryWrapper<Setmeal> setmealQueryWrapper = new LambdaQueryWrapper<>();
        setmealQueryWrapper.eq(Setmeal::getCategoryId,catetoryId);
        //返回setmeal表中 有几条条目与当前的分类id 有关联
        int setmealCount = setmealService.count(setmealQueryWrapper);
        //判断setmealCount是否大于0
        if(setmealCount>0){
            //手动抛出异常
            throw new CustomException("该分类与套餐关联 删除失败");

        }
        //3.经过前面两轮的判断 证明当前要删除的分类对象 没有与dish表和setmeal表有任何关系 则可以直接删除
        this.removeById(catetoryId);
    }
}
